/*
 * Copyright ©2021 su binglun(9085309@qq.com). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *---------------------------------------------------------------------
 *-                                                                   -
 *-           Website : http://phoenix.sunny360.cn/                   -
 *-                                                                   -
 *---------------------------------------------------------------------
 */
package cn.sunny360.core.handler.msg;

import cn.sunny360.core.common.PhResult;
import cn.sunny360.core.service.GroupService;
import cn.sunny360.core.service.MessageService;
import cn.sunny360.core.service.UserService;
import cn.sunny360.core.utils.Container;
import cn.sunny360.core.wrapper.CacheWrapper;
import cn.sunny360.messsage.MsgMessage;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.http.ServerWebSocket;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.core.json.JsonObject;
import org.joda.time.DateTime;

import java.util.List;

public class MessageAction implements MsgAction{
    private static Logger logger = LoggerFactory.getLogger(MessageAction.class);

    private MessageService messageService;
    private UserService userService;
    private GroupService groupService;
    private CacheWrapper cacheWrapper;

    public MessageAction() {
        messageService = Container.getComponent(MessageService.class);
        userService = Container.getComponent(UserService.class);
        groupService = Container.getComponent(GroupService.class);
        cacheWrapper = Container.getComponent(CacheWrapper.class);
    }

    @Override
    public Promise<PhResult> handler(Vertx vertx, ServerWebSocket webSocket, MsgMessage message) {
        Promise<PhResult> result = Promise.promise();
        //check token
        cacheWrapper.getToken("t:"+message.getFrom(), handler->{
            if (handler.succeeded()) {
                String token = (String) handler.result();
                if (token.equals(message.getToken())) {
                    processMessage(vertx, webSocket, message, result);
                } else {
                    rejectMessage(vertx, webSocket, message, result);
                }
            }
        });

        return result;
    }

    private void processMessage(Vertx vertx, ServerWebSocket webSocket, MsgMessage message, Promise<PhResult> result) {
        Promise<Long> messageSavePromise = Promise.promise();
        //保存消息
        messageService.saveMessage(new JsonObject(message.toJson()), messageSavePromise);
        messageSavePromise.future()
                .onSuccess(version->{
                    logger.info("消息已经成功保存。version：" + version);
                    //保存消息后发送OK
                    MsgMessage msgOK = MsgMessage.newInstance()
                            .setType("ok")
                            .setVersion(version)
                            .setTime(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
                    webSocket.write(Buffer.buffer(msgOK.toByteArray()));
                    //投递消息
                    message.setVersion(version);
                    Promise<PhResult> promise = deliverMessage(vertx.eventBus(), message);
                    promise.future()
                            .onFailure(result::fail)
                            .onSuccess(result::complete);
                })
                .onFailure(e->{
                    //保存消息失败后发送NG
                    MsgMessage msgNG = MsgMessage.newInstance()
                            .setType("ng")
                            .setVersion(0)
                            .setContent(e.getMessage().getBytes())
                            .setTime(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
                    webSocket.write(Buffer.buffer(msgNG.toByteArray()));
                    logger.error("保存消息失败：" , e);
                    result.fail(e);
                });
    }

    private Promise<PhResult> deliverMessage(EventBus eventBus, MsgMessage message) {
        Promise<PhResult> promise = null;
        //判断message类型
        if ("0".equals(message.getGroup())) {
            //p2p消息
            promise = deliverP2pMessage(eventBus, message);
        } else {
            promise = deliverGroupMessage(eventBus, message);
        }
        return promise;
    }

    private Promise<PhResult> deliverP2pMessage(EventBus eventBus, MsgMessage message) {
        Promise<PhResult> result = Promise.promise();
        Promise<String> checkOnlinePromise = Promise.promise();
        //将消息发送给接收者
        userService.checkOnlineStatus(new Long(message.getTo()), checkOnlinePromise);
        checkOnlinePromise.future()
                .onSuccess(token->{
                    //发送消息
                    if (!"offline".equals(token)) {
                        eventBus.send(token, Buffer.buffer().appendBytes(message.toByteArray()));
                        logger.info("向userId:" + message.getTo() + ",发送消息成功");
                    } else {
                        logger.info("userid:" + message.getTo() + "，用户不在线，无法发送消息");
                    }
                    result.complete(PhResult.ok());
                })
                .onFailure(result::fail);
        return result;
    }

    private Promise<PhResult> deliverGroupMessage(EventBus eventBus, MsgMessage message) {
        Promise<PhResult> result = Promise.promise();
        String msgTo = message.getTo();
        Promise<List<JsonObject>> listPromise = Promise.promise();
        groupService.getOnlineMemberList(Long.parseLong(msgTo), listPromise);
        listPromise.future()
                .onSuccess(list->{
                    list.stream().forEach(u->{
                        if (u.getLong("user_id") != Long.parseLong(message.getFrom())) {
                            eventBus.send(u.getString("token"), Buffer.buffer().appendBytes(message.toByteArray()));
                        } else {
                            //群消息
                            Promise<PhResult> promise = Promise.promise();
                            groupService.updateGroupVersion(Long.parseLong(message.getFrom())
                                    , Long.parseLong(message.getGroup())
                                    , message.getVersion()
                                    , promise);
                            promise.future()
                                    .onFailure(e->{
                                        logger.error("group last version update fail.", e);
                                    });
                        }
                    });
                    result.complete(PhResult.ok());
                })
                .onFailure(result::fail);
        return result;
    }

    private void rejectMessage(Vertx vertx, ServerWebSocket webSocket, MsgMessage message, Promise<PhResult> result) {
        //保存消息失败后发送NG
        MsgMessage msgReject = MsgMessage.newInstance()
                .setType("reject")
                .setVersion(0)
                .setTime(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
        webSocket.write(Buffer.buffer(msgReject.toByteArray()));
        logger.warn("拒绝消息，token不正确：" + message);
        webSocket.close();
        result.complete(PhResult.ok());
    }
}
